package com.shj.em.biz.hr.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.shj.em.aa.entity.User;
import com.shj.em.aa.mapper.UserMapper;
import com.shj.em.base.exception.BizException;
import com.shj.em.biz.hr.vo.EmpSearchDTO;
import com.shj.em.biz.report.dto.EmpEffortsDTO;
import com.shj.em.biz.sys.entity.DeptEmp;
import com.shj.em.biz.hr.entity.Emp;
import com.shj.em.biz.sys.mapper.DeptEmpMapper;
import com.shj.em.biz.hr.mapper.EmpMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.shj.em.util.DateUtils;
import com.shj.em.util.MD5Utils;
import com.shj.em.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.plugins.Page;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 员工信息 服务实现类
 *
 * @author Shen Huang Jian
 * @since 2018-07-03
 */
@Service
@Transactional
@Slf4j
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {

    @Autowired
    EmpMapper empMapper;

    @Autowired
    DeptEmpMapper deptEmpMapper;

    @Autowired
    UserMapper userMapper;

    public Page<Emp> queryEmpPage(EmpSearchDTO searchDTO){
        Page<Emp> page = new Page<>(searchDTO.getPageNo(), searchDTO.getPageSize());
        List<Emp> list = empMapper.queryEmpPage(page, searchDTO);
        return page.setRecords(list);
    }

    public boolean isUserIdExist(String userId, Long selfId){
        int cnt = empMapper.countEmpByUserId(userId, selfId);
        return cnt > 0;
    }

    public boolean insert(Emp emp){
        if(StringUtils.isNotBlank(emp.getIdCardNo())){
            emp.setBirth(getBirthdayByIdCardNo(emp.getIdCardNo()));
        }
        empMapper.insert(emp);

        // 创建与部门的对应关系
        Long id = emp.getId();
        createDeptEmp(emp.getDeptId(), id, emp.getChangeDt());

        //创建登陆表信息
        User user = new User();
        user.setUserId(emp.getUserId());
        user.setPassword(MD5Utils.encrypt(emp.getUserId(), MD5Utils.DEFAULT_PWD));
        user.setUsername(emp.getEmpName());
        userMapper.insert(user);

        return true;
    }

    private Date getBirthdayByIdCardNo(String idCard){
        if(StringUtils.isBlank(idCard)){
            return null;
        }
        String year = idCard.substring(6, 10);
        String month = idCard.substring(10, 12);
        String day = idCard.substring(12, 14);
        try {
            return DateUtils.parseDate(year + month + day, "yyyyMMdd");
        }catch (Exception e){
            return null;
        }
    }

    public boolean updateById(Emp emp){
        log.info(emp.toString());
        Emp tmp = empMapper.selectById(emp.getId());
        if(!emp.getEmpName().equalsIgnoreCase(tmp.getEmpName())){//同步用户的名字
            User user = userMapper.findByUserId(tmp.getUserId());
            user.setUsername(emp.getEmpName());
            userMapper.updateById(user);
        }

        tmp.setEmpName(emp.getEmpName());
        tmp.setSex(emp.getSex());
        tmp.setIdCardNo(emp.getIdCardNo());
        tmp.setLeaveDt(emp.getLeaveDt());
        tmp.setSheBao(emp.getSheBao());
        if(StringUtils.isNotBlank(emp.getIdCardNo())){
            tmp.setBirth(getBirthdayByIdCardNo(emp.getIdCardNo()));
        }

        tmp.setVersion(tmp.getVersion() + 1);
        empMapper.updateAllColumnById(tmp);

        // 更新与部门的对应关系
        Wrapper<DeptEmp> wrapper = new EntityWrapper<>();
        wrapper.eq("emp_id", emp.getId())
                .eq("del_flag", 0);

        List<DeptEmp> list = deptEmpMapper.selectList(wrapper);
        if(list.isEmpty()){
            createDeptEmp(emp.getDeptId(), emp.getId(), emp.getChangeDt());
        }else{
            if(list.get(0).getDeptId().equals(emp.getDeptId())){
                DeptEmp de = list.get(0);//调整日期
                de.setChangeDt(emp.getChangeDt());
                deptEmpMapper.updateById(de);
            }else{// 部门改变
                deptEmpMapper.deleteById(list.get(0).getId());
                createDeptEmp(emp.getDeptId(), emp.getId(), emp.getChangeDt());
            }
        }

        return true;
    }

    public Emp queryEmpDetailById(Long id) {
        List<Emp> empList = empMapper.queryEmpDetailById(id);
        if(empList == null || empList.isEmpty()){
            throw new BizException("找不到员工信息");
        }
        return empList.get(0);
    }

    public List<Emp> findEmpsByDeptId(Long deptId){
        return empMapper.findEmpsByDeptId(deptId);
    }

    public List<EmpEffortsDTO> findAllProdGroupTwoEmps(){
        return empMapper.findAllEmpsByProdType("erbu");
    }

    public List<EmpEffortsDTO> findAllProdGroupOneEmps(){
        return empMapper.findAllEmpsByProdType("yibu");
    }

    public List<Emp> findAllProgramEmps(){
        return empMapper.findAllProgramEmps();
    }

    private void createDeptEmp(Long deptId, Long empId, Date changeDate){
        DeptEmp de = new DeptEmp();
        de.setDeptId(deptId);
        de.setEmpId(empId);
        de.setChangeDt(changeDate);
        deptEmpMapper.insert(de);
    }
}
